package com.ex.util;

import javax.servlet.http.HttpServletRequest;

/**
 * web 相关的工具类
 *
 * @author zhouxl
 * @DATE 2020/11/26
 * @descriptoin
 */
public class WebUtil {

    /**
     * 获取客户端ip地址信息
     *
     * @param request
     * @return
     */
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader(" x-forwarded-for ");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 判断当前请求是否是jsonp请求
     * true  - 是jsonp请求
     * false - 非jsonp请求
     *
     * @param request HttpServletRequest
     * @return
     */
    public static boolean isJsonpRequest(HttpServletRequest request) {
        String callbackparam = request.getParameter("callbackparam");
        if (callbackparam != null &&
                "jsonpCallback".toLowerCase().equals(callbackparam)) {
            return true;
        }
        return false;
    }

    /**
     * 判断当前是否是ajax请求
     * true  - 是ajax请求
     * false - 非ajax请求
     *
     * @param request HttpServletRequest
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestType = request.getHeader("x-requested-with");
        if (requestType == null) {
            return false;
        }
        return "XMLHttpRequest".toLowerCase().equals(requestType.trim().toLowerCase());
    }

}
